package service

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/emailBox"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/email/utils"
	"strings"
	"time"
)

type EmailService struct{}

//@author: [maplepie](https://github.com/maplepie)
//@function: EmailTest
//@description: 发送邮件测试
//@return: err error

func (e *EmailService) EmailTest() (err error) {
	subject := "test"
	body := "test"
	err = utils.EmailTest(subject, body)
	return err
}

//@author: [maplepie](https://github.com/maplepie)
//@function: EmailTest
//@description: 发送邮件测试
//@return: err error
//@params to string 	 收件人
//@params subject string   标题（主题）
//@params body  string 	 邮件内容

func (e *EmailService) SendEmail(to, subject, body string) (err error) {
	err = utils.Email(to, subject, body)
	return err
}

func (e *EmailService) SendEmailByFrom(uuid, to, subject, body string) (err error) {
	var emailConfig emailBox.EmailConfig
	err = global.GVA_DB.Where("uuid = ?", uuid).First(&emailConfig).Error
	if err != nil {
		return err
	}
	emailConfig.HostName = `smtp.qq.com`
	//port, _ := strconv.Atoi(emailConfig.Port)
	port := 465
	To := strings.Split(to, ",")
	err = utils.SendByFrom(emailConfig.EmailAddress, "", emailConfig.EmailPassword, emailConfig.HostName, port, true, To, subject, body)
	if err != nil {
		return err
	}
	var emailINBOX emailBox.EmailINBOX
	emailINBOX.EmailTo = to
	emailINBOX.EmailFrom = emailConfig.EmailAddress
	emailINBOX.EmailSubject = subject
	emailINBOX.EmailContentHtml = body
	emailINBOX.EmailContentText = body
	var emailtime time.Time = time.Now()
	emailINBOX.EmailDate = &emailtime
	emailStatus := 4
	emailINBOX.Status = &emailStatus
	emailINBOX.Auth = uuid
	err = global.GVA_DB.Create(&emailINBOX).Error
	return err
}
